package com.chookss.home.inspection;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.aliyun.svideo.common.utils.NetUtils;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.home.audit.service.UploadInspectionService;
import com.chookss.home.entity.InspectionEntity;
import com.chookss.tools.FileUtilss;
import com.chookss.tools.GridSpacingItemDecoration;
import com.chookss.tools.MyToast;
import com.chookss.tools.PathUtil;
import com.chookss.tools.PermissionUtils;
import com.chookss.tools.Utils;
import com.chookss.tools.bigImage.ImagePreview;
import com.chookss.tools.bigImage.bean.ImageInfo;
import com.chookss.view.ImageFileCompressEngine;
import com.chookss.view.MyRoundLayout;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.lvgroup.hospital.base.BaseAct;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnCancelListener;
import com.lxj.xpopup.interfaces.OnConfirmListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
//巡检发布
public class InspectionPublishActivity extends BaseAct {
    @BindView(R.id.common_title_txt)
    TextView commonTitleTxt;
    @BindView(R.id.common_right_iv)
    ImageView commonRightIv;
    @BindView(R.id.common_right_iv_ll)
    LinearLayout common_right_iv_ll;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.edContent)
    EditText edContent;
    private MyImagsAdapter adapter;
    private ArrayList<String> list = new ArrayList<>();
    private ArrayList<Map<String, String>> urlListMaps = new ArrayList<>();
    private int numAll = 0;
    private String groupCode, groupName, firstUrl;
    private InspectionEntity inspectionEntity;
    public LocationClient mLocationClient = null;
    private MyLocationListener myListener = new MyLocationListener();
    private String locAddress = "";
    private String locWd="", locJd="";//app定位经纬度
    private Bitmap bitmap;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        setContentView(R.layout.activity_inspection_publish);
        ButterKnife.bind(this);
    }

    @Override
    public void initData() {
        initState();
        commonTitleTxt.setText("巡检");
        inspectionEntity = (InspectionEntity) getIntent().getSerializableExtra("data");
        firstUrl = getIntent().getStringExtra("url");
        groupName = getIntent().getStringExtra("groupName");
        groupCode = getIntent().getStringExtra("groupCode");
        list.add("");
        GridLayoutManager gridLayoutManager1 = new GridLayoutManager(this, 3);
        recyclerView.setLayoutManager(gridLayoutManager1);
        GridSpacingItemDecoration gridSpacingItemDecoration = new GridSpacingItemDecoration(3, Utils.dip2px(this, 12), false);
        recyclerView.addItemDecoration(gridSpacingItemDecoration);
        adapter = new MyImagsAdapter(R.layout.item_my_news, this, list);
        recyclerView.setAdapter(adapter);
        if (NetUtils.isGPSEnabled(this)) {
            initWaterData();
            getPermissions();
        } else {
            showDialog();
        }
    }
    private void showDialog() {
        new XPopup.Builder(this)
                .isDestroyOnDismiss(true)
                .dismissOnTouchOutside(false)
                .asConfirm("提示", "定位服务未开启，请打开定位服务",
                        "取消", "去开启",
                        new OnConfirmListener() {
                            @Override
                            public void onConfirm() {
                                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                startActivity(intent);
                                finish();
                            }
                        }, new OnCancelListener() {
                            @Override
                            public void onCancel() {
                                finish();
                            }
                        }, false)
                .show();
    }
    private void getPermissions() {
        XXPermissions.with(this)
                // 申请单个权限
                .permission(Permission.ACCESS_FINE_LOCATION)
                .permission(Permission.ACCESS_COARSE_LOCATION)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (all) {
                            startLoc();
                        } else {
                            MyToast.show("定位权限未正常授予");
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {
                            MyToast.show("被永久拒绝授权，请手动授予定位权限");
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(InspectionPublishActivity.this, permissions);
                        } else {
                            MyToast.show("获取定位权限失败");
                        }
                    }
                });
    }
    private void startLoc() {
        //声明LocationClient类
        try {
            if (mLocationClient == null) {
                LocationClient.setAgreePrivacy(true);
                mLocationClient = new LocationClient(getApplicationContext());
                LocationClientOption option = new LocationClientOption();
                mLocationClient.registerLocationListener(myListener);
                option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
                option.setCoorType("bd09ll");
                option.setIsNeedAddress(true);
                option.setOpenGps(true);
                option.setScanSpan(1000);
                mLocationClient.setLocOption(option);
            }
            if (mLocationClient != null) {
                mLocationClient.start();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void initWaterData() {
        Observable.timer(300, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) {
                        if (!Utils.isNull(firstUrl)){
                            try {
                                bitmap= BitmapFactory.decodeFile(firstUrl,getBitmapOption(2));
                                list.add(0, WaterMaskUtil.saveWaterMask(InspectionPublishActivity.this,bitmap, inspectionEntity.getAddressName(), groupName, inspectionEntity.getAddressAccuracyX(), inspectionEntity.getAddressAccuracyY()));
                                adapter.notifyDataSetChanged();
                                FileUtilss.delFile(firstUrl);
                            } catch (Exception e) {
                                if(list.size()>1){
                                    list.remove(0);
                                }
                                throw new RuntimeException(e);
                            }
                        }
                    }
                });

    }


    class MyImagsAdapter extends BaseQuickAdapter<String, BaseViewHolderEx> {
        private Context context;
        private int width, height;

        public MyImagsAdapter(int layoutResId, Context context, @io.reactivex.annotations.Nullable List<String> data) {
            super(layoutResId, data);
            this.context = context;
            width = (Utils.getScreenWidthPixel(context) - Utils.dip2px(context, 48)) / 3;
            height = width;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, String item) {
            MyRoundLayout myRl = helper.getView(R.id.myRl);
            ImageView ivBg = helper.getView(R.id.ivBg);
            LinearLayout llDelete = helper.getView(R.id.llDelete);
            LinearLayout llAdd = helper.getView(R.id.llAdd);
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) myRl.getLayoutParams();
            params.height = height;
            params.width = width;
            myRl.setLayoutParams(params);
            RelativeLayout.LayoutParams llAddParams = (RelativeLayout.LayoutParams) llAdd.getLayoutParams();
            llAddParams.height = height;
            llAddParams.width = width;
            llAdd.setLayoutParams(llAddParams);
            if (Utils.isNull(item)) {
                llAdd.setVisibility(View.VISIBLE);
                myRl.setVisibility(View.GONE);
            } else {
                llAdd.setVisibility(View.GONE);
                myRl.setVisibility(View.VISIBLE);
                Glide.with(InspectionPublishActivity.this).load(item).into(ivBg);
            }
            llDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    list.remove(helper.getItemPosition());
                    if (list.size() < 9 && !Utils.isNull(list.get(list.size() - 1))) {
                        list.add("");
                    }
                    adapter.notifyDataSetChanged();
                }
            });
            llAdd.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    requestCamera();
                }
            });
            myRl.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    List<ImageInfo> imageInfoList = new ArrayList<>();
                    ImageInfo imageInfo = new ImageInfo();
                    imageInfo.setThumbnailUrl(item);
                    imageInfo.setOriginUrl(item);
                    imageInfoList.add(imageInfo);
                    ImagePreview.getInstance()
                            .setContext(context)
                            // 设置从第几张开始看（索引从0开始）
                            .setIndex(0)
                            .setShowCloseButton(true)
                            .setToNewView(false)
                            .setShowDownButton(false)
                            .setLoadStrategy(ImagePreview.LoadStrategy.AlwaysOrigin)
                            .setImageInfoList(imageInfoList)
                            .start();
                }
            });
        }
    }


    private void requestCamera() {
        XXPermissions.with(this)
                .permission(Permission.CAMERA)
                .permission(Permission.Group.STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> granted, boolean all) {
                        if (all) {
                            openCamera();
                        }
                    }

                    @Override
                    public void onDenied(List<String> denied, boolean quick) {
                        PermissionUtils.errorPermission(InspectionPublishActivity.this, denied, quick);
                    }
                });
    }

    private void openCamera() {
        PictureSelector.create(this)
                .openCamera(SelectMimeType.ofImage())
                .setCompressEngine(ImageFileCompressEngine.createGlideEngine())
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {
                        if(result!=null){
                            if(result.size()>0){
                                String url = "";
                                if (!Utils.isNull(result.get(0).getCompressPath())) {
                                    if (result.get(0).getCompressPath().contains("content://")) {
                                        Uri uri = Uri.parse(result.get(0).getCompressPath());
                                        url = PathUtil.getPath(InspectionPublishActivity.this, uri);
                                    } else {
                                        url = result.get(0).getCompressPath();
                                    }
                                } else {
                                    if (result.get(0).getPath().contains("content://")) {
                                        Uri uri = Uri.parse(result.get(0).getPath());
                                        url = PathUtil.getPath(InspectionPublishActivity.this, uri);
                                    } else {
                                        url = result.get(0).getPath();
                                    }
                                }
                                KLog.i(System.currentTimeMillis());
                                if(!Utils.isNull(url)) {
                                    String oldUrl = url;
                                    if (!Utils.isNull(locAddress)) {
                                        inspectionEntity.setAddressAccuracyX(locJd);
                                        inspectionEntity.setAddressAccuracyY(locWd);
                                        inspectionEntity.setAddressName(locAddress);
                                    }
                                    bitmap=BitmapFactory.decodeFile(url, getBitmapOption(2));
                                    url = WaterMaskUtil.saveWaterMask(InspectionPublishActivity.this, bitmap, inspectionEntity.getAddressName(), groupName, inspectionEntity.getAddressAccuracyX(), inspectionEntity.getAddressAccuracyY());
                                    if (!list.contains(url)) {
                                        list.add(list.size() - 1, url);
                                    }
                                    if (list.size() == 10) {
                                        list.remove(9);
                                    }
                                    adapter.notifyDataSetChanged();
                                    FileUtilss.delFile(oldUrl);
                                }else{
                                    MyToast.show("拍照异常，请重试");
                                }
                            }
                        }
                    }

                    @Override
                    public void onCancel() {

                    }
                });
    }

    private BitmapFactory.Options getBitmapOption(int inSampleSize) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = inSampleSize;
        // 优化内存配置
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        options.inMutable = true; // 允许修改 Bitmap 像素
        return options;
    }
    @OnClick({R.id.common_title_back, R.id.common_right_iv_ll, R.id.tvSure})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
            case R.id.common_right_iv_ll:
                Intent intent = new Intent(this, InspectionGalleryListActivity.class);
                startActivity(intent);
                break;
            case R.id.tvSure:
                if (Urls.antiShake.check()) {
                    return;
                }
                if (list.size() <= 1) {
                    MyToast.show("请至少添加一张图片");
                    return;
                }
                Intent intentUpload = new Intent(InspectionPublishActivity.this, UploadInspectionService.class);
                inspectionEntity.setGroupCode(groupCode);
                inspectionEntity.setGroupName(groupName);
                inspectionEntity.setXunjianRemarks(edContent.getText().toString());
                inspectionEntity.setPicList(list);
                intentUpload.putExtra("inspectionEntity", inspectionEntity);
                startService(intentUpload);
                finish();
                break;
        }
    }
    private int locationFlag = 0;
    private boolean firstLocation=true;
    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location != null) {
                locationFlag++;
                if (!Utils.isNull(location.getAddrStr())) {
                    locWd = location.getLatitude() + "";
                    locJd = location.getLongitude() + "";
                    locAddress=location.getAddrStr();
                }else {
                    if(firstLocation){
                        if (mLocationClient != null) {
                            firstLocation=false;
                            mLocationClient.start();
                        }
                    }
                }

                if (locationFlag >= 6 && !Utils.isNull(locWd)) {
                    locationFlag = 0;
                    if (mLocationClient != null) {
                        mLocationClient.stop();
                    }
                }
            }else {
                if(firstLocation){
                    if (mLocationClient != null) {
                        firstLocation=false;
                        mLocationClient.start();
                    }
                }
            }

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mLocationClient != null) {
            mLocationClient.stop();
        }
        if(bitmap!=null){
            bitmap.recycle();
            bitmap=null;
        }
    }
}
